<template>
  <view>
    <image src="../../image/bg.png" class="bgImg" />
    <view class="top-title" :style="{height:customBar+'px',paddingTop:statusBar+'px'}">
      <view class="top-title-back" @tap="goBack">
        <image src="../../image/back.png" />
      </view>
      <text class="top-title-t1">续费</text>
    </view>
    <view class="card-title">
      <text class="card-title-t1">月租卡</text>
      <text class="card-title-t2" v-if="lastDays>0&&lastDays<10||lastDays==0">剩余{{lastDays}}天</text>
      <text class="card-title-t3" v-if="lastDays<0" style="color: #666;">已过期</text>
    </view>
    <view class="card">
      <image src="../../image/cardbg.png" class="img" />
      <view class="card-right">
        <view class="rt-p1" v-if="carInfos.plates>20" style="font-size:28rpx;line-height:1.5">
          <image src="../../image/car.png" class="rt-img1" />&nbsp;
          <text>{{carInfos.plates}}</text>
        </view>
        <view class="rt-p1" v-else>
          <image src="../../image/car.png" class="rt-img1" />&nbsp;
          <text>{{carInfos.plates}}</text>
        </view>
        <view class="rt-p2">{{carInfos.park&&carInfos.park.parkName||"暂无车场数据"}}</view>
        <view class="rt-p3" v-if="endTime!==''">有效期:{{startTime.substring(0, 10)}} ~ {{endTime.substring(0, 10)}}</view>
      </view>
    </view>
    <view class="money">
      <view class="title">选择延期时长</view>
      <view
        v-for="(item,index) in navTab"
        :key="index"
        @tap="currentTab(item)"
        :class="active==index ? 'active' : ''"
      >
        <text>{{item.time}}</text>
        <text>{{item.value}}元</text>
      </view>
      <view class="box1">
        <input
          placeholder="请输入续费时长(单位月)"
          v-model="value"
          type="number"
          class="inp1"
          @blur="bindKeyInput(value)"
        />
        <text class="box1-p1">个月</text>
      </view>
    </view>
    <view class="btn" @tap="goRecharge">支付{{amount}}元</view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./monthRecharge.less";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import bulterApi from "@souche2014/bulter-api";
import { request } from "../../util/axios.js";
const api = bulterApi({ partner: "IOParking" });
// pages/card/storeRecharge.js
var common = require("../../common.js");
export default {
  data() {
    return {
      mobile: "",
      openId: "",
      navTab: [
        //由于本地端不结束时分秒，所以未开始开始时间加一天，已过期结束减一
        {
          time: "1个月",
          value: "",
          index: 0,
          months: 1
        },
        {
          time: "1季度",
          value: "",
          index: 1,
          months: 3
        },
         {
          time: "半年",
          value: "",
          index: 2,
          months: 6
        },
        {
          time: "1年",
          value: "",
          index: 3,
          months: 12
        }
      ],
      active: 0, //默认一个月
      dialog1: false,
      showKeyboard: true,
      carnum: "",
      showKeyboard: false,
      addPlate: false,
      plateList: [],
      currentPlate: 0,
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头
      id: 0,
      chargId:null,//卡的id
      carInfos: {
        plates: "",
        park: { parkName: "" }
      },
      lastDays: 0,
      amount: 0,
      feeTemplate: null,
      startTime: "", //月租卡续费开始时间（显示）
      beginTime:'',//月租卡续费开始时间（传值）
      endTime: "", //月租卡续费结束时间
      statusBar: 0,//状态栏高度
      customBar:0,//胶囊按钮高度
      value: "",
      date:new Date()//激活时间
    };
  },
   mounted(){
    Taro.getSystemInfo({
      success:(res)=> {
        this.statusBar = res.statusBarHeight; //状态栏高度
        let custom = Taro.getMenuButtonBoundingClientRect(); //菜单按钮
        this.customBar = custom.height+8;
        console.log(this.statusBar,this.customBar);
      }
    });
  },
  onLoad: function(options) {
    this.initData(options.id);
    this.id = options.id;
    this.date=common.formatTime(new Date(), "Y-M-D")
  },
  methods: {
    initData(id) {
      var that = this;
      var base = this.apiBaseUrl;
      Taro.request({
        url: base + "/parkingpayment/getparkingtoken?id=" + id,
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          console.log(res.data);
          if (res.data.isSuccess) {
            that.carInfos = res.data.data;
            that.chargId=res.data.data.chargId
            that.feeTemplate = JSON.parse(res.data.data.feeTemplate.ruleDetail);
            let chargingStandard = that.feeTemplate.chargingStandard;
            if (chargingStandard.length == 3) {
              that.navTab[2].time = "年卡";
              that.navTab.pop();
            } else if (chargingStandard.length == 4) {
              that.navTab[3].value = chargingStandard[3].pmr_unit_price;
            }
            that.navTab[0].value = chargingStandard[0].pmr_unit_price;
            that.navTab[1].value = chargingStandard[1].pmr_unit_price;
            that.navTab[2].value = chargingStandard[2].pmr_unit_price;
            that.getFeediscountinfo()
            var t1 = new Date(that.carInfos.endDate.replace(/-/g, "/"));
            var t2 = new Date();
            var t = new Date(t1 - t2 + 16 * 3600 * 1000);
            console.log(t1,t2,t)
            var timeDay = parseInt(t.getTime() / 1000 / 3600 / 24);
            that.lastDays = timeDay;
            that.months=1
            that.getResultInfos()
          }
        }
      });
    },
     //计算缴费结果
    getResultInfos() {
      var that = this;
      //月租卡已过期
      let beginTime=''
      if (that.lastDays < 0) {
        beginTime = common.formatTime(new Date(), "Y-M-D h:m:s");
        that.startTime=beginTime
      } else {
        //未过期
        beginTime = that.mathChangeDate(that.carInfos.endDate,'+',1)
        that.startTime=that.carInfos.startDate
      }
      var base = that.apiBaseUrl;
      Taro.request({
        url: base + "/onlinepayment/getcostinfo",
        header: {
          "content-type": "application/json" // 默认值
        },
        data: {
          feeId: +that.chargId,
          months: +that.months,
          beginTime:beginTime
        },
        method: "POST",
        success(res) {
          if (res.data.isSuccess) {
            that.amount = res.data.data.amount;
            that.endTime = res.data.data.endTime;
            that.beginTime=res.data.data.beginTime;
          }else{
            Taro.showToast({
              title: res.data.message,
              icon: "none",
              duration: 1000,
              mask: true
            });
          }
        }
      });
    },
    getFeediscountinfo(){
      var that = this;
      var base = this.apiBaseUrl;
      let params = {
        feeId: that.chargId
      };
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      Taro.request({
        url: base + "/onlinepayment/feediscountinfo",
        data: params,
        method: "POST",
        success(res) {
          Taro.hideLoading();
          if (res.data.isSuccess) {
             let feeTemplate = JSON.parse(res.data.data.chargStandard);
              console.log(feeTemplate);
              let chargingStandard = feeTemplate;
              if (chargingStandard.length == 3) {
                that.navTab[2].time = "年卡";
                that.navTab.pop();
              } else if (chargingStandard.length == 4) {
                that.navTab[3].value = chargingStandard[3].pmr_unit_price;
                that.navTab[3].original = chargingStandard[3].pmr_original_price;
              }
              that.navTab[0].value = chargingStandard[0].pmr_unit_price;
              that.navTab[1].value = chargingStandard[1].pmr_unit_price;
              that.navTab[2].value = chargingStandard[2].pmr_unit_price;
              that.navTab[0].original = chargingStandard[0].pmr_original_price;
              that.navTab[1].original = chargingStandard[1].pmr_original_price;
              that.navTab[2].original = chargingStandard[2].pmr_original_price;
              that.amount = that.navTab[0].value;
          }
        }
      });
    },
    goRecharge(e) {
      var that = this;
      var base = this.apiBaseUrl;
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      Taro.request({
        url: base + "/onlinepayment/renew",
        data: {
          tokenId: that.carInfos.id,
          amount: that.amount,
          payAmount: that.amount,
          discountAmount: 0,
          carType: that.carInfos.type,
          startTime: that.beginTime.substring(0, 10),
          endTime: that.endTime.substring(0, 10),
          parkId: that.carInfos.parkId,
          mobile: getGlobalData("mobile") || "",
          wxOpenId: getGlobalData("openId"),
          months:that.months
        },
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "POST",
        success(res) {
          Taro.hideLoading();
          console.log(res);
          if (res.data.isSuccess) {
            // var orderId = res.data.data.chargeOrderId
            that.wxPay(res.data.data.wxPayOrderParams);
          } else {
            Taro.showToast({
              title: "下单失败",
              icon: "error",
              duration: 1000,
              mask: true
            });
          }
        }
      });
    },
    wxPay(obj, orderId) {
      //微信支付
      var that = this;
      Taro.requestPayment({
        timeStamp: obj.timeStamp,
        nonceStr: obj.nonceStr,
        package: obj.package,
        signType: obj.signType,
        paySign: obj.paySign,
        success(res) {
          console.log("支付成功");
          api.bury("monthNum", {
              time: new Date().valueOf(),
              mobile: getGlobalData("mobile") || "",
              parkName:that.carInfos.park.parkName,
              parkId:that.carInfos.parkId
            });
          Taro.navigateTo({
            url: "../openCard/paySuccess"
          });
        },
        fail(res) {
          console.log(res);
        }
      });
    },
    bindKeyInput(e) {
      var re = /^[1-9]\d*$/;
      if (e > 0) {
        if (re.test(e)) {
          this.months = e;
          this.active = -1; //13
         this.getResultInfos()
        }
      } else {
        // Taro.showToast({
        //   title: "最低1个月",
        //   icon: "error",
        //   duration: 1000,
        //   mask: true
        // });
        // this.amount = this.navTab[0].value;
        // this.value = "";
        // this.active = 0;
      }
    },
    goBack() {
      Taro.navigateBack({
        delta: 1
      });
    },
    bindDateChange: function(e) {
      this.date= e.detail.value
    },
    mathChangeDate(date, method, days) {
      //当前日期加减天数
      //method:'+' || '-'  new Date(item.endDate.replace(/-/g, '/'))时间格式苹果兼容处理
      var timestamp = Date.parse(date.replace(/-/g, "/"));
      if (method == "+") {
        timestamp = timestamp / 1000 + 24 * 60 * 60 * days;
      } else if (method == "-") {
        timestamp = timestamp / 1000 - 24 * 60 * 60 * days;
      }
      let time = this.toDate(timestamp);
      return time;
    },
    toDate(number) {
      var n = number;
      var date = new Date(parseInt(n) * 1000);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
    currentTab(e) {
      //充值金额切换
      console.log(e)
      var that = this;
      if (that.currentTab == e.index) {
        return;
      }
      that.active = e.index;
      that.months = e.months;
      that.value=''
      that.getResultInfos();
    },
    shijiancha(faultDate, completeTime) {
      var stime = Date.parse(new Date(faultDate));
      var etime = Date.parse(new Date(completeTime));
      var usedTime = etime - stime; //两个时间戳相差的毫秒数
      var days = Math.floor(usedTime / (24 * 3600 * 1000));
      //计算出小时数
      var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));
      //计算相差分钟数
      var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));
      var dayStr = days == 0 ? "" : days + "天";
      var hoursStr = hours == 0 ? "" : hours + "时";
      var time = dayStr + hoursStr + minutes + "分";
      return time;
    },
    num(a) {
      if (a != null && a.toString() != "") {
        let r = /^-?(0|[1-9]+\d*|[1-9]+\d*\.\d+|0\.\d+)$/;
        if (r.test(a.toString())) {
          return true;
        }
      }
      return false;
    },
    //加法
    plus(a, b) {
      if (!this.num(a) || !this.num(b)) {
        return null;
      }
      let c, d, m, n;
      try {
        c = a.toString().split(".")[1].length;
      } catch (e) {
        c = 0;
      }
      try {
        d = b.toString().split(".")[1].length;
      } catch (e) {
        d = 0;
      }
      m = Math.pow(10, Math.max(c, d));
      return (a * m + b * m) / m;
    }
  }
};
</script>
